﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Transactions;
using Bids.Data;
using Bids.Core.DomainObjects;
using Bids.Core.Infrastructure;
using Bids.Core.Common.Data;
using Bids.Core.Common.Pager;

namespace Bids.Web.Controllers.Admin
{

    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
          
            var admin = filterContext.HttpContext.Session["admin"];

            if (admin == null)
            {
                filterContext.RequestContext.HttpContext.Response.Redirect("/Admin/Login");
                filterContext.RequestContext.HttpContext.Response.End();
            }

        }

    }

    [UserAuthorize]
    public class BaseController<T> : Controller where T : IEntity
    {
        protected IRepository<T> _iRpoT;
        protected string orderString;
        protected string conditionString;
        public BaseController(IRepository<T> iRpoT)
        {
            _iRpoT = iRpoT;
        }
        /// <summary>
        /// 首页列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public virtual ActionResult Index(int page = 1)
        {
            OrderString();
            ConditionString();
           

            int listRows = 10;

            //处理搜索
            string Search_Field = Request["Search_Field"];
            string Search_Compare = Request["Search_Compare"];
            string Search_Key = Request["Search_Key"];
            string Search_Page = Request["listRows"];
            if (Search_Page != null)
            {
                listRows = int.Parse(Search_Page);
            }

            string Condition = conditionString;

            if (Search_Field != null && Search_Key != null)
            {

                switch (Search_Compare)
                {
                    case "Like":
                        Condition = Condition + " and " + Search_Field + ".Contains(\"" + Search_Key + "\")";
                        break;
                }

            }

            IQueryable<T> list = _iRpoT.Where(Condition, orderString);

            //TempData["EModel"] = list;//导出的数据

            PagedList<T> li = list.ToPagedList(page, listRows);

            SetReturnUrl();

            return View(li);
        }

        /// <summary>
        /// 新增页面
        /// </summary>
        /// <returns></returns>
        public virtual ActionResult Create()
        {
           
            return View();
        }
        /// <summary>
        /// 新增操作
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult Create(T model)
        {
            try
            {

                _iRpoT.Add(model);
                SetMessage("新增成功", true);
                return GetReturnUrl();
            }
            catch (Exception e)
            {
                SetMessage(e.Message.ToString().Replace("\r\n", "\\r\\n"), false);
                return RedirectToAction("Index");
            }
        }
        /// <summary>
        /// 修改页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual ActionResult Edit(int id)
        {

            var m = _iRpoT.Find(id);
            return View(m);
        }

        /// <summary>
        /// 修改操作
        /// </summary>
        /// <param name="id"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult Edit(int id,T moel)
        {
            try
            {
                var m = _iRpoT.Find(id);
                UpdateModel(m);
                _iRpoT.Update(m);
                SetMessage("修改成功", true);
                return GetReturnUrl();
            }
            catch (Exception e)
            {
                SetMessage(e.Message.ToString().Replace("\r\n", "\\r\\n"), false);
                return RedirectToAction("Index");
            }
        }

        /// <summary>
        /// 删除多项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual ActionResult Deletes(string id)
        {

            try
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    foreach (var item in id.Split(','))
                    {

                        var del = _iRpoT.Find(item.ToInt32());
                        if (del != null)
                            _iRpoT.Remove(del);
                    }
                    ts.Complete();
                    SetMessage("删除成功", true);
                    return GetReturnUrl();
                }
            }
            catch (Exception e)
            {
                SetMessage(e.Message.ToString().Replace("\r\n", "\\r\\n"), false);
                return RedirectToAction("Index");
            }
        }

        public virtual ActionResult Delete(int id)
        {
            try
            {
                var del = _iRpoT.Find(id);
                if (del != null)
                    _iRpoT.Remove(del);
                SetMessage("删除成功", true);
                return GetReturnUrl();
            }
            catch (Exception e)
            {
                SetMessage(e.Message.ToString().Replace("\r\n", "\\r\\n"), false);
                return RedirectToAction("Index");
            }
        }

        public virtual void OrderString()
        {
            orderString = "ID Desc";
        }

        public virtual void ConditionString()
        {
            conditionString = "1=1";
        }


        //设置返回链接
        public void SetReturnUrl()
        {
            TempData[ControllerContext.RouteData.GetRequiredString("controller") + "ReturnUrl"] = Request.Url;
        }

        //获取返回链接
        public ActionResult GetReturnUrl(string urlAction = "")
        {
            string returnValue = "";

            if (TempData[ControllerContext.RouteData.GetRequiredString("controller") + "ReturnUrl"] != null)
            {
                returnValue = TempData[ControllerContext.RouteData.GetRequiredString("controller") + "ReturnUrl"].ToString();
                return Redirect(returnValue);
            }
            else if (urlAction != "")
            {
                return RedirectToAction(urlAction);
            }

            return RedirectToAction("Index");
        }

        //设置信息
        public void SetMessage(string msg, bool type)
        {
            if (type)
            {
                TempData["Message"] = "<span class=\"successMsg\">" + msg + "</span>";
            }
            else
            {
                TempData["Message"] = "<span class=\"errorMsg\">" + msg + "</span>";
            }
        }


    }
}
